/* eslint-disable camelcase */
/* eslint-disable react/no-string-refs */
import './css/index.less';

class TextEdit extends React.Component {
    defaultProps = {
        value: '',
        desc: '',
        placeholder: '',
        limitCount: 0,
        callback: () => {},
        cancelCallback: () => {},
        notEmoji: false,
        canEmpty: false,
        isListener: false,
    };

    componentDidMount() {
        this.$J_Page = $('#J_Page');
        this.$J_Page.hide();
        const textareaHeight = $(window).height()
            - $(this.refs.wrap)
                .find('.topBox')
                .height()
            - $(this.refs.wrap)
                .find('.txtNum')
                .height();
        $(this.refs.textarea).height(textareaHeight);
        this.moveEnd($(this.refs.textarea));
        $('body').scrollTop(0);
        this.check();
    }

    componentWillUnmount() {
        this.$J_Page.show();
    }

    $J_Page = $('#J_Page .curPage');

    scrollTop = $(window).scrollTop();

    save = () => {
        this.refs.textarea.value = this.refs.textarea.value.replace(/<[^>]+>/g, '');

        if (!this.props.canEmpty && this.refs.textarea.value.length < 1) {
            this.refs.textarea.blur();
            WPT.Modal.alert('填写的内容不得为空');
            return false;
        }
        this.props.close();
        this.$J_Page.show();
        $(window).scrollTop(this.scrollTop);
        this.props.callback && this.props.callback(this.refs.textarea.value);
        this.props.isListener && window.history.back();
        return null;
    };

    cancel = () => {
        this.props.close();
        this.$J_Page.show();
        $(window).scrollTop(this.scrollTop);
        this.props.cancelCallback && this.props.cancelCallback();
        this.props.isListener && window.history.back();
    };

    moveEnd(obj) {
        if (obj.length) {
            // eslint-disable-next-line prefer-destructuring
            obj = obj[0];
            // obj.focus();
            const len = obj.value.length;
            if (document.selection) {
                const sel = obj.createTextRange();
                sel.moveStart('character', len);
                sel.collapse();
                sel.select();
            } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
                // eslint-disable-next-line no-multi-assign
                obj.selectionStart = obj.selectionEnd = len;
            }
        }
    }

    check = () => {
        const $textarea = this.refs.textarea;
        $textarea.focus();
        const limit = parseInt(this.props.limitCount);
        let value = $textarea.value || '';
        if (this.props.notEmoji) {
            const filteremoji = val => {
                const ranges = ['\ud83c[\udf00-\udfff]', '\ud83d[\udc00-\ude4f]', '\ud83d[\ude80-\udeff]'];
                return val.replace(new RegExp(ranges.join('|'), 'g'), '');
            };
            value = filteremoji(value);
            $textarea.value = value;
        }
        if (limit && value.length > limit) {
            value = value.substr(0, limit);
            $textarea.value = value;
        }
        $(this.refs.wrap)
            .find('.txtNum')
            .text(`${value.length} / ${this.props.limitCount}`);
    };

    render() {
        const setPosition = $.os.phone ? { position: 'fixed' } : {};
        return (
            <div className="modules_textEdit" style={setPosition} ref="wrap">
                <div className="topBox">
                    <div className="head">
                        <div className="fl cancel" {...WPT.onTouchEnd(this.cancel)}>
                            取消
                        </div>
                        <div className="fr save" {...WPT.onTouchEnd(this.save)}>
                            保存
                        </div>
                    </div>
                    <div className={`desc${this.props.desc ? ' fullDesc' : ''}`}>
                        {this.props.desc ? this.props.desc : ''}
                    </div>
                </div>
                {!!this.props.limitCount && <div className="txtNum" />}
                <textarea
                    className="textEdit_textarea"
                    onChange={this.check}
                    ref="textarea"
                    autoFocus
                    placeholder={this.props.placeholder}
                    defaultValue={this.props.value}
                />
            </div>
        );
    }
}

export default function (options = {}) {
    const instance = WPT.Modal.open(<TextEdit {...options} />, {
        animation: false,
        fullScreen: true,
        position: 'bottom',
        layerStyle: {
            opacity: 0,
        },
    });
    if (options.isListener) {
        WPT.pushState(WPT.curUrl);
        const closeListenner = () => {
            window.removeEventListener('popstate', closeListenner);
            instance.close();
        };
        window.addEventListener('popstate', closeListenner);
    }
    return instance;
}
